<template>
    <div class="subject-management">
      <el-card class="card" :class="{ 'hover': isHover }" @mouseover="isHover = true" @mouseleave="isHover = false">
        <template #header>
          <div class="card-header">
            <div class="title">标签管理</div>
            <div v-show="!addExamineDialogVisible">
              <button class="add-btn btn" type="primary" @click="addExamine"><i class="animation"></i>添加题目标签<i
                  class="animation"></i></button>
            </div>
          </div>
        </template>
        <el-table :data="pageData" style="width: 100%;" border>
          <el-table-column width="" prop="label" label="题目标签" align="center">
            <!-- <template #default="{ row }">
              <el-tooltip placement="top">
                <template #content>目标描述：{{ row.target_content }}</template>
                <div>{{ row.target_name }}</div>
              </el-tooltip>
            </template> -->
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="{ row, $index }">
              <el-button @click="editExamineTarget(row, $index)" type="primary" plain size="mini">编辑</el-button>
              <el-button @click="deleteExamineTarget(row)" type="danger" plain size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div ref="addEditBoxRef" style="display:none;" id="add-examine-form" class="add-examine-form">
          <!-- <div v-show="addExamineDialogVisible"  ref="addEditBoxRef" style="display:none;width:100%" class="add-examine-form"> -->
          <div style="padding: 5px 10px;font-size: 20px;margin: 10px auto;">{{ newExamine.id ? '编辑题目标签' : '添加题目标签'}}</div>
          <div style="display: flex;justify-content: center;;margin: 10px auto;">
            <div class="addLeft">
              <!-- <p>添加题目标签</p> -->
              <div style="padding: 5px 10px;">标签名字：</div>
                  <div style="width: 70%;">
                      <el-form  :model="newExamine" label-position="left">
                          <el-input v-model="newExamine.label"></el-input>
                      </el-form>
                  </div>
            </div>
                <div>
                  <el-button @click="confirmAddExamine">{{ newExamine.id ? "确定编辑" : "确定添加" }}</el-button>
                  <el-button @click="cancelAddExamine">取消</el-button>
                </div>
              </div>
            <!-- </el-form> -->
          <!-- </div> -->
        </div>

        <el-pagination style="width:100%; margin-top: 30px;text-align: center;justify-content: center;" v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]" :small="false" :background="true"
            layout="total, sizes, prev, pager, next, jumper" :total="filteredData.length"
            @size-change="handleSizeChange" @current-change="handleCurrentPageChange" />
      </el-card>
      <!-- <router-view></router-view> -->
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, watch,computed } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { addCourseObjectives, getAllCourseObjectives, deleteCourseObjectives, updateCourseObjectives, getIdCourseObject } from "@/api/course.js"
  import { getAllExamineContent,addTitleTag,updateTitleTag,getTagContent,deleteTitleTag } from '@/api/tag.js'
  import { formatTime } from '@/utils/format'
  import { useUserStore, useClassStore } from '@/stores/index'

  
  const editingRowIndex = ref(null); // 当前编辑的行的索引
  // const showAddButtons = ref(false);
  const examineArr = reactive([]);
  const isHover = ref(false);
  const addExamineDialogVisible = ref(false);
  const lookDescribeDialogVisible = ref(false)
  const showDescribe = ref('')
  const newExamine = reactive({
    id: null,
    target_name: '',//考核目标
    target_desc: [''],//考核内容
    target_content: '',//课程目标描述
    sub_id: 0,
    label:''
    // num: 1
  });
const pageSize = ref(10);//初始化页面时题目的数量
const currentPage = ref(1);
const dataArr = ref([])

const filteredData = computed(() => {
    let data = [...examineArr];
    // if (searchId.value) {
    //     data = data.filter(item => item.id.includes(searchId.value));
    // }
    // if (searchSubject.value) {
    //     data = data.filter(item => item.subject.includes(searchSubject.value));
    // }
    // if (searchType.value) {
    //     data = data.filter(item => item.type.includes(searchType.value));
    // }
    // if (searchContent.value) {
    //     data = data.filter(item => item.questionContent.includes(searchContent.value));
    // }
    return data;
});

const pageData = computed(() => {
    // const startIndex = (currentPage.value - 1) * pageSize.value;
    // return filteredData.value.slice(startIndex, startIndex + pageSize.value);
    //根据id由高到低
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const sortedData = filteredData.value.slice().sort((a, b) => b.id - a.id);
    return sortedData.slice(startIndex, startIndex + pageSize.value);
});

const handleCurrentPageChange = (page) => {
    currentPage.value = page;
}

const handleSizeChange = (val) => {
    pageSize.value = val;
}
  
  const addEditBoxRef = ref(null);
  //编辑功能
  const editExamineTarget = (row, index) => {
    console.log(row,index,'222');
    const editBox = document.querySelector('.add-examine-form');
    if (editBox) {
      editBox.style.display = 'block'
  
      const targetRow = document.querySelectorAll('.el-table__body-wrapper tbody tr')[index]
      targetRow.parentNode.insertBefore(editBox, targetRow.nextSibling)
    }
    console.log(index, 'index');
    editingRowIndex.value = index;
    addExamineDialogVisible.value = true
    // 编辑功能代码
    console.log(row, 'row.id');
    newExamine.id = row.id
    newExamine.label = row.label
    // newExamine.target_name = row.target_name
    // newExamine.target_content = row.target_content
    // newExamine.target_desc = row.target_desc;
    // console.log(newExamine,'999');
    const boxWidth = document.getElementById('add-examine-form')
    if(pageData.value.length === 0){
      console.log('22',pageData.value.length);
      boxWidth.style.width = '200%'
      console.log('000');
    }else{
      console.log('88');
      boxWidth.style.width = '200%'
    }
  };
  
  //删除功能
  const deleteExamineTarget = async (row) => {
    // console.log(row,'rererer');
    const confirmResult = await ElMessageBox.confirm('是否删除', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      target_name: 'warning'
    }).catch(() => {
      ElMessage({ type: 'info', message: '删除取消' });
    });
  
    if (confirmResult === 'confirm') {
      const res = await deleteTitleTag(row.id)
      if(res.data.code === 400){
        ElMessage({ type: 'error', message: `${res.data.msg}` });
        return 
      }
      // 删除功能代码
      examineArr.splice(examineArr.indexOf(row), 1);
      // console.log(row.id,'111');
      console.log(res.data.code,'2222222222');
      ElMessage({ type: 'success', message: '删除成功' });
    }
  };
  
  //添加题目标签
  const addExamine = () => {
    addExamineDialogVisible.value = true

    const editBox = document.querySelector('.add-examine-form');
    if (editBox) {
      editBox.style.display = 'block'
  
      // 将编辑框追加到表格最后一个元素后面
      // const lastRow = document.querySelector('.el-table__body-wrapper tbody tr:last-child');
      // lastRow.parentNode.appendChild(editBox);

      // 将编辑框追加到表格最前面
      const firstRow = document.querySelector('.el-table__body-wrapper tbody tr:first-child');
      firstRow.parentNode.insertBefore(editBox, firstRow);
    }
    const boxWidth = document.getElementById('add-examine-form')
    if(pageData.value.length === 0){
      console.log('22',pageData.value.length);
      boxWidth.style.width = '200%'
      console.log('000');
    }else{
      console.log('88');
      boxWidth.style.width = '200%'
    }
  }
  
  
  //增加考核内容输入框
  const addNewExamineContent = () => {
    newExamine.target_desc.push('');
    // newExamine.target_desc = [...newExamine.target_desc, ''];
  };
  
  const deleteArr = ref([])
  //delete考核内容
  const deleteNewExamineContent = () => {
    if (newExamine.target_desc.length > 1) {
      if (!newExamine.target_desc[newExamine.target_desc.length - 1]) {
        // console.log(newExamine.target_desc[newExamine.target_desc.length-1],'!newExamine.target_desc[newExamine.target_desc.length]');
        newExamine.target_desc.pop()
      } else {
        deleteArr.value.push(newExamine.target_desc[newExamine.target_desc.length - 1])
        console.log(deleteArr.value, 'length');
        newExamine.target_desc.pop()
      }
    } else {
      ElMessage({ type: 'error', message: '最少得有一个考核内容！' })
    }
  }
  
  //取消添加考核
  const cancelAddExamine = async () => {
    // if (deleteArr.value.length > 0) {
    //   deleteArr.value.forEach(item => {
    //   })
    // }
  
    //方法一
    //  getIdCourseObject(newExamine.id).then((res)=>{
    //   console.log("kzyt",res.data.data);
    //  })
    //根据课程目标的id获取存储在数据库的数据
    // 11
    // if (newExamine.id) {
  
    //   const res = await getIdCourseObject(newExamine.id)
    //   const responseArr = res.data.data
  
    //   examineArr.forEach((item) => {
  
    //     if (responseArr.id === item.id) {
    //       // item.id = responseArr.id
    //       item.target_name = responseArr.target_name
    //       item.target_content = responseArr.target_content
    //       item.target_desc = responseArr.target_desc;
  
    //     }
    //   })
    // ElMessage({ type: 'info', message: '取消编辑' });

    // }
    if(newExamine.id) ElMessage({ type: 'info', message: '取消编辑' });
    else ElMessage({ type: 'info', message: '取消添加' });
    //方法二
    // console.log(newExamine.target_desc, 'newExamine.target_desc');
    addAndEditDialogBox()
  };

  // 关闭添加编辑框
  const addAndEditDialogBox = () =>{
    addExamineDialogVisible.value = false;
    newExamine.id = null
    // newExamine.target_name = '';
    // newExamine.target_content = ''
    // newExamine.target_desc = [''];
    newExamine.label = ''
    const editBox = document.querySelector('.add-examine-form');
    if (editBox) {
      editBox.style.display = 'none'
    }
  }

  //确定添加考核
  const confirmAddExamine = async () => {
    if (newExamine.id) {
      const data = {
        // id: newExamine.id,
        // createdAt: newExamine.updatedAt,
        // sub_id: newExamine.sub_id,
        // target_content: newExamine.target_content,
        // target_desc: newExamine.target_desc,
        // target_name: newExamine.target_name,
        id:newExamine.id,//标签id
        label:newExamine.label
      }
  
      const res2 = await updateTitleTag(data)
      ElMessage({ type: 'success', message: '编辑成功' });
      
      examineArr.forEach((value,index) =>{
        if(value.id === data.id){
          examineArr[index].label = newExamine.label
        }
      })

      addExamineDialogVisible.value = false;
      newExamine.id = null
      newExamine.target_name = '';
      newExamine.target_content = '';
      newExamine.target_desc = [''];

      addAndEditDialogBox()//关闭对话框
  
    } else {
      const data = {
        sub_id:newExamine.sub_id,
        label:newExamine.label,
      }
      const res = await addTitleTag(data)
      console.log(res.data, '1234');
      const res1 = res.data.data
      console.log(res1,'resss11');
      // examineArr.push({
      //   id: res1.newTarget.id,
      //   sub_id: res1.newTarget.sub_id,
      //   // id:examineArr.length++,
      //   target_name: res1.newTarget.target_name,
      //   target_desc: res1.newTarget.target_desc,
      //   target_content: res1.newTarget.target_content,
      //   createdAt: res1.newTarget.createdAt,
      //   updatedAt: res1.newTarget.updatedAt
      // });
      examineArr.push({
        id:res1.id,
        label:res1.label,
        sub_id:res1.sub_id
      })
  
      addExamineDialogVisible.value = false;
      // newExamine.target_name = '';
      // newExamine.target_content = '';
      // newExamine.target_desc = [''];
      newExamine.label = '';
  
      ElMessage({ type: 'success', message: '添加成功' });
      addAndEditDialogBox()//关闭对话框
      // newExamine.num = 1;
    }
  };
  // //确定添加考核
  // const confirmAddExamine = async () => {
  //   //every它的作用是用来检查数组中所有元素是否满足指定条件，content.trim() 是将 content 值去除首尾空格后的结果
  //   // if () {
  //   console.log('fdf44444');
  //   if (!(newExamine.target_name && newExamine.target_content && newExamine.target_desc.every(content => content.trim() !== ''))) {
  //     ElMessage({ type: 'warning', message: '请填写完整信息' });
  //     return
  //   }
  
  //   // 检查是否存在相同的课程目标
  //   // 如果是编辑 课程目标有相同的则返回true && 而且判断是不同的id之间的课程目标 true ==> true
  //   // 如果是编辑 课程目标没有相同的则返回false && 而且判断是不同的id之间的课程目标 true ==> false
  //   console.log(examineArr,'examineArrexamineArrexamineArr');
  //   const isDuplicate = examineArr.some(item => item.target_name === newExamine.target_name && item.id !== newExamine.id);
  //   if (isDuplicate) {
  //     ElMessage({ type: 'warning', message: '不能添加相同的课程目标' });
  //     return;
  //   }
  
  //   // 检查是否有重复的考核内容
  //   // 如果是编辑 考核内容有相同的则返回true && 如果相同的考核内容的id和编辑项的id是不相同的话 true ==> true
  //   // 如果是编辑 考核内容有相同的则返回true && 如果相同的考核内容的id和编辑项的id是相同的id的话 false ==> false
  
  //   const isDuplicateDesc = examineArr.some(item => item.target_desc.some(desc => newExamine.target_desc.includes(desc)) && item.id !== newExamine.id);
  //   if (isDuplicateDesc) {
  //     ElMessage({ type: 'warning', message: '不能添加重复的考核内容' });
  //     return;
  //   }
  
  //   if (newExamine.id) {
  //     const data = {
  //       id: newExamine.id,
  //       createdAt: newExamine.updatedAt,
  //       sub_id: newExamine.sub_id,
  //       target_content: newExamine.target_content,
  //       target_desc: newExamine.target_desc,
  //       target_name: newExamine.target_name,
  //     }
  
  //     const res2 = await updateCourseObjectives(data)
  //     ElMessage({ type: 'success', message: '编辑成功' });
  
  //     addExamineDialogVisible.value = false;
  //     newExamine.id = null
  //     newExamine.target_name = '';
  //     newExamine.target_content = '';
  //     newExamine.target_desc = [''];
  
  //   } else {
  //     const res = await addCourseObjectives(newExamine)
  //     console.log(res.data, '1234');
  //     const res1 = res.data.data
  //     console.log(res1.newTarget, 'res1');
  //     examineArr.push({
  //       id: res1.newTarget.id,
  //       sub_id: res1.newTarget.sub_id,
  //       // id:examineArr.length++,
  //       target_name: res1.newTarget.target_name,
  //       target_desc: res1.newTarget.target_desc,
  //       target_content: res1.newTarget.target_content,
  //       createdAt: res1.newTarget.createdAt,
  //       updatedAt: res1.newTarget.updatedAt
  //     });
  
  //     addExamineDialogVisible.value = false;
  //     newExamine.target_name = '';
  //     newExamine.target_content = '';
  //     newExamine.target_desc = [''];
  
  //     ElMessage({ type: 'success', message: '添加成功' });
  //     // newExamine.num = 1;
  //   }
  // };
  
  //点击叉关闭对话框后清除里面输入框的样式
  const handleClose = () => {
    addExamineDialogVisible.value = false;
    newExamine.target_name = '';
    newExamine.target_desc = [''];
    lookDescribeDialogVisible.value = false
  }
  
  const lookExamineDescribe = (row) => {
    lookDescribeDialogVisible.value = true
    showDescribe.value = row
  }
  
  //关闭查看课程描述窗口
  const cancelLookDescribe = () => {
    lookDescribeDialogVisible.value = false
  }

  const subInfo = reactive({
  syllabusId:0,
  subId:0,
  class_name:'',
  grade_name:'',
  subject:'',
})
//一进入页面，则把该班级的大纲id给页面
const classMessage = useClassStore()
// syllabusId.value = classMessage.classInfo.id
subInfo.syllabusId = classMessage.classInfo.user_and_acs_id//大纲id
subInfo.subId = classMessage.classInfo.subId
subInfo.class_name = classMessage.classInfo.class_name
subInfo.grade_name = classMessage.classInfo.grade_name
subInfo.subject = classMessage.classInfo.subject

  const getAllTagInfo = async () => {
    examineArr.value = []
    //科目id
    const res = await getTagContent(subInfo.subId)
    console.log(res,'subInfo.subId');
    const res1 = res.data.data
    res.data.data.forEach((response) => {
      // const data = {
      //   id: response.id,
      //   createdAt: response.createdAt,
      //   sub_id: response.sub_id,
      //   target_content: response.target_content,
      //   target_desc: response.target_desc,
      //   target_name: response.target_name,
      //   updatedAt: response.updatedAt
      // }
      examineArr.push(response)
    })
    console.log('arr', examineArr);
  }
    
  onMounted(() => {
    // 模拟初始化数据
    getAllTagInfo()

    newExamine.sub_id = subInfo.subId;

  });
</script>
  
  <style scoped>
  .subject-management{
    box-sizing: border-box;
  }
  .card {
    /* width: 900px; */
    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, .1);
    transition: box-shadow .3s ease;
    box-sizing: border-box;
    /* 加上这一属性后，padding和border的值就不会再影响元素的宽高了 */
  }
  
  .hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, .2);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .title {
    font-size: 20px;
    font-weight: bold;
  }
  
  .add-btn {
    margin-right: 0;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
  
  .add-btn {
    margin-top: 20px;
  }
  
  .ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .add-examine-form {
    /* width:200%; */
    height:100px;
    display: flex;
    /* border:1px solid black; */
    border: 1px solid #D9E8FC;
    /* margin-left: 10px; */
    /* margin-top: 10px; */
    box-sizing: border-box;
      /* margin:center; */
      /* justify-content:space-between; */
      /* margin-left:200px;  */
      text-align: center;
      align-items: center;
      justify-content: center;
      background-color: #D9E8FC;
  }
  
  
  .addLeft {
    display:flex;
    width: 100%;
    text-align: center;
    /* padding: 0 10px; */
    text-align: center;
  }
  
  .addRight {
    /* flex: 1;
      padding: 0 10px; */
    width: 40%;
      align-items: center;
    /* padding: 0 10px; */
    /* 可根据需要调整 */
  }
  
  .addLeft,
  .addRight {
    width: 40%;
    /* 让两个子元素各占容器的40%宽度 */
    padding: 0 10px;
    box-sizing: border-box;
    /* 确保内边距不会增加元素的实际宽度 */
  }
  
  
  .btn {
    outline: 0;
    display: inline-flex;
    align-items: center;
    justify-content: space-between;
    background: #96b6e6;
    min-width: 200px;
    /* width: 100%; */
    border: 0;
    border-radius: 4px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, .1);
    box-sizing: border-box;
    padding: 16px 20px;
    color: #fff;
    font-size: 12px;
    font-weight: 600;
    letter-spacing: 1.2px;
    text-transform: uppercase;
    overflow: hidden;
    cursor: pointer;
  }
  
  .btn:hover {
    opacity: .95;
  }
  
  .btn .animation {
    border-radius: 100%;
    animation: ripple 0.6s linear infinite;
  }
  
  @keyframes ripple {
    0% {
      box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.1), 0 0 0 20px rgba(255, 255, 255, 0.1), 0 0 0 40px rgba(255, 255, 255, 0.1), 0 0 0 60px rgba(255, 255, 255, 0.1);
    }
  
    100% {
      box-shadow: 0 0 0 20px rgba(255, 255, 255, 0.1), 0 0 0 40px rgba(255, 255, 255, 0.1), 0 0 0 60px rgba(255, 255, 255, 0.1), 0 0 0 80px rgba(255, 255, 255, 0);
    }
  }
  
  .target_desc_class::after {
    content: "";
    display: block;
    width: 80px;
    height: 1px;
    background: linear-gradient(244deg, rgba(255, 255, 255, 0) 0%, rgb(134, 198, 231) 50%);
  }
  </style>